package com.caac.core.web.action.user;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.caac.core.dm.Menu;
import com.caac.core.dm.Role;
import com.caac.core.service.UserManager;
import com.caac.core.web.action.BaseAction;
import com.caac.core.web.form.BaseForm;
import com.caac.core.web.form.PermissionForm;
import com.caac.core.web.view.PermissionView;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright 2004</p>
 * <p>Company: </p>
 * @author <a href="mailto:lianzs@agilecentury.com">lianzs</a>
 * @version 1.0
 */

public class SearchPermissionAction extends BaseAction {
    protected ActionForward doExecute(ActionMapping mapping, BaseForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response) throws java.
            lang.Exception {
        PermissionForm psf = (PermissionForm) form;
        UserManager um = (UserManager)this.getBean("userManager");

        List mList = um.getAllMenus();
        List rList = um.getAllRoles();
        psf.setActionList(mList);
        psf.setRoleList(rList);

        List vList = new ArrayList();
        for (int i = 0; i < mList.size(); i++) {
            PermissionView pView = new PermissionView();
            Menu menu = (Menu) mList.get(i);
            pView.setMenu(menu);
            List rvList = new ArrayList();
            for (int j = 0; j < rList.size(); j++) {
                rvList.add(findPermission((Role) rList.get(j), menu.getMenuCode()));
            }
            pView.setChkList(rvList);
            vList.add(pView);
        }

        request.setAttribute("vlist", vList);
        request.setAttribute("rlist", rList);
        return this.forward(mapping);
    }

    private LabelValueBean findPermission(Role role, Integer menuKey) {

        for (Iterator it = role.getMenus().iterator(); it.hasNext(); ) {
            Menu menu = (Menu) it.next();
            if (menuKey.equals(menu.getMenuCode())) {
                return new LabelValueBean("JS" + role.getId() + menuKey, "1");
            }
        }
        return new LabelValueBean("JS" + role.getId() + menuKey, "0");
    }
}
